package com.google.code.sfa.util;


import com.google.code.sfa.parse.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class PotentialOverlaps {

    private HashMap<Trace,Integer> _matches;
    private HashSet<Trace> _alreadyTried;

    public PotentialOverlaps() {
	_matches = new HashMap<Trace,Integer>();
	_alreadyTried = new HashSet<Trace>();
    }

    public void add( Trace t, int matches) {
	if( _alreadyTried.contains( t) ) {
	    return;
	}

	if( _matches.containsKey(t) ) {
	    _matches.put( t, _matches.get(t) + matches);
	} else {
	    _matches.put( t, matches);
	}
    }

    public void addAll( Map<Trace,Integer> matches) {
	if( matches != null) {
	    for( Trace t : matches.keySet() ) {
		add( t, matches.get(t));
	    }
	}
    }

    public Trace next() {
	Trace best = null;
	int bestMatches = 0, matches;
	for(Trace t : _matches.keySet()) {
	    if( best == null) {
		best = t;
		bestMatches = _matches.get(t);
	    } else {
		matches = _matches.get(t);
		if( !t.isRepeat() && best.isRepeat() || 
		    (t.isRepeat() == best.isRepeat() && 
		     matches > bestMatches )) {

		    best = t;
		    bestMatches = matches;
		}
	    }
	}
	if( best != null) {
	    _matches.remove(best);
	    _alreadyTried.add( best);
	}
	return best;
    }

    public boolean hasNext() {
	return _matches.size() > 0;
    }
}
		
